from django.contrib.auth import authenticate
from django.contrib.auth.models import User
from django.shortcuts import render

from commodity.models import Types, CommodityInfos
from django.http import HttpResponse
from django.shortcuts import render

# Create your views here.

# def shopperView(request):
#     return HttpResponse('Hello World!')

# def loginView(request):
#     title = "用户登录"
#     classContent = "logins"
#     if request.method == "POST":
#         username = request.POST.get("username","")
#         password = request.POST.get("password","")
#         if User.objects.filter(username=username):
#             user = authenticate(username=username, password=password)
#             if user:
#                 login(request, user)
#                 return redirct(reversed('shopper:shoppe'))
#             else:
#                 state='注册成功'
#                 d=dict(username=username,password=password,is_staff=1,isactive=1)
#                 user=User.objects.create_user(**d)
#                 user.save()
#     return HttpResponse('Hello World!')

# def logoutView(request):
#     return HttpResponse('Hello World!')
#
# def shopcartView(request):
#     return HttpResponse('Hello World!')
def shopperView(request):
    return HttpResponse("Hello, world. You're at the polls page.")

# def loginView(request):
#     return render(request, "login.html")

def logoutView(request):
    return HttpResponse("Logged out.")

def shopcartView(request):
    return render(request, "shopcart.html")

def loginView(request):
    """
    用户登录视图函数，处理用户登录请求，
    支持现有用户认证和新用户注册
    """
    # 定义变量title和classContent用于设置公用模板base.html的模板变量
    title = "用户登录"
    classContent = "logins"
    # 对用户的请求方式进行判断
    if request.method == "POST":
        # 如果是POST请求，那么视图函数会执行注册和登录操作
        # 获取请求参数username和password
        username = request.POST.get('username', "")
        password = request.POST.get('password', "")
        # 查询username的数据是否存在于内置模型User
        if User.objects.filter(username=username):
            # 验证账号和密码是否与模型User中对应的一致
            user = authenticate(username=username, password=password)
            # 如果通过验证，使用内置函数login执行登录操作，登录成功后
            # 跳转到个人中心页面
            if user:
                login(request, user)
                return redirect(reverse('shopper:shopper'))
        else:
            # username不存在于内置模型User，执行注册
            state = "注册成功"
            d = dict(username=username, password=password, is_staff=1, is_active=1)
            user = User.objects.create_user(**d)
            user.save()
    return render(request, 'login.html', locals())